const fs = require('fs')
const Koa = require('koa')
const Router = require('koa-router')
const koaBody = require('koa-body')
const etag = require('koa-etag')
const conditional = require('koa-conditional-get')
const history = require('koa2-history-api-fallback')
const logger = require('./server/logger')
const log4js = require('log4js')

const { port } = require('./env.conf')

const router = new Router({
  prefix: '/q'
})

const controllers = fs
  .readdirSync('./server/controller')
  .filter(s => /\.ctrl\.js$/i.test(s))
controllers.forEach(f => {
  logger.info(`register api: ${f}`)
  f = f.replace('.js', '')
  const ctrl = require(`./server/controller/${f}`)
  ctrl && ctrl(router)
})
const app = new Koa()
app.keys = ['some secret hurr']

app.use(
  koaBody({
    // 支持文件上传
    multipart: true,
    strict: false,
    formidable: {
      maxFieldsSize: 1000 * 1024 * 1024 * 1024
    }
  })
)

app.use(
  history({
    verbose: false,
    rewrites: [
      {
        from: /^\/api\/.*$/,
        to: function (context) {
          logger.info(`【history】 redirect to: ${context.parsedUrl.path}`)
          return context.parsedUrl.path
        }
      }
    ]
  })
)

// etag 304
app.use(conditional())
app.use(etag())

app.use(router.routes())
app.listen(port)
app.on('error', (err, ctx) => {
  logger.error(`server error, ${err}, ${ctx}`)
})
logger.info(`server is listening on port: ${port}`)
const terminate = () => {
  logger.info('server is offline...')
  log4js.shutdown()
  process.exit()
}
process.on('warning', e => logger.warn(`node warn`, e.stack))
process.on('uncaughtException', (e, origin) =>
  logger.warn(`node uncaughtException: ${e}, exception origin: ${origin}`)
)
process.on('SIGINT', terminate)
process.on('SIGTERM', terminate)
